package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/3/15 0015.
 */

public class BindBankActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.ed_name)
    EditText edName;
    @Bind(R.id.ed_zh)
    EditText edZh;
    @Bind(R.id.bank)
    TextView bank;
    @Bind(R.id.bank_type)
    TextView bankType;
    @Bind(R.id.bind)
    TextView bind;
    private String sessionId;
    private String seceret;

    @Override
    public int bindLayout() {
        return R.layout.activity_bank_card;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        title.setText("绑定银行卡");
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        getSessionId();
        bind.setEnabled(false);
        bankType.setText(sp.getString("OpeningBank", ""));
        edName.setText(sp.getString("userName",""));
        edZh.setText(sp.getString("BankaCardId",""));
        bank.setText(sp.getString("AffiliatedBank",""));
        edZh.addTextChangedListener(textWatcher);
        edName.addTextChangedListener(textWatcher);
        back.setOnClickListener(this);
        bind.setOnClickListener(this);
        edName.setSelection(edName.getText().toString().length());
        if(!TextUtils.isEmpty(edName.getText()) & !TextUtils.isEmpty(edZh.getText()) & !TextUtils.isEmpty(bank.getText()) & !TextUtils.isEmpty(bankType.getText())){
            bind.setBackgroundResource(R.drawable.edittext_red_style);
            bind.setEnabled(true);
        }
    }

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!TextUtils.isEmpty(edZh.getText()) && edZh.getText().toString().length() >= 15) {
                GetBankInfo();
            }
            if (!TextUtils.isEmpty(edName.getText()) && !TextUtils.isEmpty(bank.getText())) {
                bind.setBackgroundResource(R.drawable.edittext_red_style);
                bind.setEnabled(true);
            }
        }
    };

    public void GetBankInfo() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetBankcard(sessionId, edZh.getText().toString().trim(), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Card" + edZh.getText().toString().trim())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    bank.setText(json.getString("message"));
                    bankType.setText(json.getString("num"));
                    if (!TextUtils.isEmpty(edName.getText()) && !edName.getText().toString().equals("")) {
                        bind.setBackgroundResource(R.drawable.edittext_red_style);
                        bind.setEnabled(true);
                    } else {
                        bind.setBackgroundResource(R.drawable.edittext_style_dark);
                        bind.setEnabled(false);
                    }
                } else {
                    bank.setText("");
                    bankType.setText("");
                    bind.setBackgroundResource(R.drawable.edittext_style_dark);
                    bind.setEnabled(false);
                    ToastUtils.getInstance(BindBankActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void BindBank() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap<String, Object> map = new HashMap();
        map.put("UserPhone", sp.getString("userPhone", ""));
        map.put("UserName", edName.getText().toString());
        map.put("CardType", bankType.getText().toString().trim());
        map.put("BankaCardId", edZh.getText().toString());
        map.put("AffiliatedBank", bank.getText().toString().trim());
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetUserBankCard(sessionId, map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "AffiliatedBank" + bank.getText().toString().trim() + "BankaCardId" + edZh.getText().toString().trim() + "CardType" + bankType.getText().toString().trim() + "UserName" + edName.getText().toString().trim() + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(BindBankActivity.this).showMessage(json.getString("message"));
                    finish();
                } else {
                    ToastUtils.getInstance(BindBankActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    public void getSessionId() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    sessionId = json.getString("message");
                    seceret = json.getString("data");
                    editor.putString("seceret", seceret);
                    editor.apply();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.bind: {
                if (bind.isEnabled()) {
                    BindBank();
                }
            }
            break;
            default:
                break;
        }
    }
}
